package com.powernode.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.Notice;
import com.powernode.mapper.NoticeMapper;
import com.powernode.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import static com.powernode.constant.NoticeConstant.FRONT_NOTICE_LIST;

@Service
@CacheConfig(cacheNames = "com.powernode.service.impl.NoticeServiceImpl")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService{
    @Autowired
    private NoticeMapper noticeMapper;

    @Override
    public void selectNoticePage(Page<Notice> page, Notice notice) {

        noticeMapper.selectPage(page, new LambdaQueryWrapper<Notice>()
                .eq(ObjectUtil.isNotEmpty(notice.getStatus()), Notice::getStatus, notice.getStatus())
                .eq(ObjectUtil.isNotEmpty(notice.getIsTop()), Notice::getIsTop, notice.getIsTop())
                .like(StrUtil.isNotEmpty(notice.getTitle()), Notice::getTitle, notice.getTitle())
                .orderByDesc(Notice::getIsTop, Notice::getPublishTime)
        );
    }

    @Override
    @Cacheable(key = FRONT_NOTICE_LIST)
    public List<Notice> loadFrontNotice() {
        return noticeMapper.selectList(new LambdaQueryWrapper<Notice>()
            .eq(Notice::getStatus, 1).orderByDesc(Notice::getIsTop)
        );
    }

    @Override
    @CacheEvict(key = FRONT_NOTICE_LIST)
    public boolean save(Notice entity) {
        entity.setUpdateTime(new Date());
        Integer status = entity.getStatus();
        if (1 == status) {
            entity.setPublishTime(new Date());
        }

        return noticeMapper.insert(entity) > 0;
    }

    @Override
    @CacheEvict(key = FRONT_NOTICE_LIST)
    public boolean updateById(Notice entity) {
        entity.setUpdateTime(new Date());

        return noticeMapper.updateById(entity) > 0;
    }

    @Override
    @CacheEvict(key = FRONT_NOTICE_LIST)
    public boolean removeById(Serializable id) {
        return noticeMapper.deleteById(id) > 0;
    }
}
